package com.wxchat.chat.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;

public class DBUtils {
	private static String driver;
	private static String url;
	private static String name;
	private static String pass;
	/**
	 * 获取数据源的信息
	 * */
	static {
		driver = ResourceBundle.getBundle("db").getString("jdbc.driverClass");
		url = ResourceBundle.getBundle("db").getString("jdbc.jdbcUrl");
		name = ResourceBundle.getBundle("db").getString("jdbc.user");
		pass = ResourceBundle.getBundle("db").getString("jdbc.password");
	}
	static Connection connection = null;
	static ResultSet resultSet = null;
	static PreparedStatement preparedStatement = null;
	static PreparedStatement preparedStatementTow = null;
	//获取Connection
	public static Connection getConnection() throws Exception {
		Class.forName(driver);
		connection = DriverManager.getConnection(url, name, pass);
		if (connection != null) {
			System.out.println("ok");
		} else {
			System.out.println("no");
		}
		return connection;
	}
	/**
	 * 增删改的公共的方法
	 * */
	public static boolean executeSQL(String sql, Object[] obj) {
		try {
			connection = DBUtils.getConnection();
			preparedStatement = connection.prepareStatement(sql);
			if (obj != null && obj.length > 0) {
				for (int i = 0; i < obj.length; i++) {
					preparedStatement.setObject(i + 1, obj[i]);
				}
			}
			int in = preparedStatement.executeUpdate();
			if (in > 0) {
				System.out.println("ok");
				return true;
			} else {
				System.out.println("失败");
				return false;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DBUtils.colse(connection, null, preparedStatement);
		}
		return false;
	}

	/**
	 * 关闭资源
	 * */
	public static void colse(Connection con, ResultSet res, PreparedStatement pre) {
		if (con != null) {
			try {
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (res != null) {
			try {
				res.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (pre != null) {
			try {
				pre.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}
